<script setup>
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  DelDataAPI,
  GetDeiltsAPI,
  DispatchAPI,
  MaintenanceAPI,
  SubmitAPI,
  AuditAPI,
  AddKnowLedgeAPI,
  BatchAuditAPI,
  RatchRevocationAPI,
} from "@/api/device/repair.js";
import WorkOrder from "./workOrder.vue";
import Maintenance from "./maintenance.vue";
import Failure from "./failure.vue";
const router = useRouter();
const route = useRoute();
// import useUserStore from '@/store/modules/user'
// vue3方法实例
const { proxy } = getCurrentInstance();
const { equipment_repair_status } = proxy.useDict("equipment_repair_status");

// 报修 || 修改 || 查看实例
const WorkOrderRef = ref(null);
/**
 * 故障信息
 */
const FailureRef = ref(null);
/**
 * 维修信息
 */
const MaintenanceRef = ref(null);

/**
 * 批量表单实例
 */
const ruleFormRef = ref(null);
// const userStore = useUserStore()
// 标签页
const tabPosition = ref("1");

// 储存数据
const ruleForm = ref({});

// 各种状态及小数据
const state = reactive({
  row: [], // 选中数据
  ids: "", // 选中id
  delDisabled: false, // 多选
  examineDisabled: false, // 单选
  btnloading: false, //保存加载状态
  total: 0, // 列表总数量
  isShow: false, // 新增弹窗状态
  title: "报修", // 标题
  loading: false, // 表格加载状态
  examineShow: false, //审核弹窗
  rows: [],
  examineBatchShow: false, //批量审核
});

// 按钮枚举
const btnList = ref([]);
/**
 * 按钮控制
 */
const delDisabled = ref(true);
// 列表数据
const tabelData = ref([]);
// 表单校验
const rules = reactive({
  auditOpinion: [
    { required: true, message: "请填写审核意见", trigger: "blur" },
  ],
});
// 列表枚举
const column = ref([
  { label: "维修单号", prop: "repairCode", width: "180" },
  { label: "紧急程度", prop: "repairUrgentDict", width: "120" },
  { label: "单据状态", prop: "repairState", width: "120" },
  { label: "设备编码", prop: "deviceCode", width: "120" },
  { label: "故障类型", prop: "repairFailureType", width: "120" },
  { label: "故障内容", prop: "knowledgeFailureContent", width: "120" },
  { label: "设备名称", prop: "deviceName", width: "120" },
  { label: "设备类型", prop: "deviceType", width: "120" },
  { label: "设备型号", prop: "deviceUnitType", width: "120" },
  { label: "设备位置", prop: "installationLocation", width: "120" },
  { label: "故障描述", prop: "repairFailureDescription", width: "120" },
  { label: "报修时间", prop: "repairWarrantyTime", width: "120" },
  { label: "维修时长", prop: "repairTime", width: "120" },
  { label: "维修班组", prop: "teamName", width: "120" },
  { label: "操作", prop: "x" },
]);

// 查询条件
const SelectList = ref([
  { label: "维修单号", model: "repairCode", type: "输入框" },
  { label: "设备编码", model: "deviceCode", type: "输入框" },
  { label: "设备名称", model: "deviceName", type: "输入框" },
  { label: "设备位置", model: "installationLocation", type: "设备位置" },
  { label: "派工时间", model: "repairDispatchTime", type: "派工时间" },
  { label: "报修时间", model: "repairWarrantyTime", type: "日期范围" },

  {
    label: "维修状态",
    model: "repairState",
    type: "下拉单选",
    opt: equipment_repair_status,
  },
]);

// 查询条件 分页
const query = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 初始化按钮
const initBtn = () => {
  btnList.value = [
    {
      label: "新增",
      type: "add",
      hasPermi: "device:repair:equipment:add",
    },
    // {
    //   label: '派工',
    //   type: '自定义',
    //   hasPermi: 'device:equipment:dispatch',
    //   emit: 'dispatch',
    //   disabled: delDisabled,
    // },
    {
      label: "撤销单据",
      type: "自定义",
      hasPermi: "device:repair:equipment:revoke",
      emit: "revoke",
      disabled: delDisabled,
    },

    {
      label: "提交审核",
      type: "自定义",
      hasPermi: "device:repair:equipment:subExamine",
      emit: "review",
      disabled: delDisabled,
    },

    {
      label: "审核单据",
      type: "自定义",
      hasPermi: "device:repair:equipment:examine",
      emit: "examine",
      disabled: delDisabled,
    },
  ];
};
initBtn();

// 条件查询
const selectSubmit = (obj) => {
  console.log(obj, "obj");

  Object.keys(obj).forEach((itemKey) => (query[itemKey] = obj[itemKey]));
  query.startTime1 = typeof query.Time == "string" ? "" : query.Time[0];
  query.endTime1 = typeof query.Time == "string" ? "" : query.Time[1];
  query.startTime2 = query.beginTime;
  query.endTime2 = query.endTime;
  query.repairId = "";
  getList();
};

// 勾选列表数据时
const handleSelectionChange = ({ ids, row }) => {
  state.ids = ids;
  state.rows = row;
  state.multipleDis = !row.length;
  state.singleDis = row.length != 1;
  delDisabled.value = row?.length == 0 || !row;
  console.log(delDisabled.value, "delDisabled.value");

  initBtn();
};
handleSelectionChange({ ids: [], row: [] });

// 报修弹窗
const repair = () => {
  tabPosition.value = "1";
  state.title = "新增";
  state.isShow = true;
};

// 派工弹窗
const workers = async (id) => {
  state.title = "派工";
  tabPosition.value = "3";
  proxy.loading("请求中，请稍后");
  try {
    // const { data: res } = await GetDeiltsAPI(id)
    // ruleForm.value = res
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 执行维修弹窗
const maintenance = async (id) => {
  state.title = "执行维修";
  tabPosition.value = "3";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    // if (!res.repairBy.includes(userStore.name)) return proxy.warningMsg('只能是派工成员执行维修！')
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 提交审核弹窗
const subAudit = async (id) => {
  const isif = await proxy.MessageBox("确认提交审核吗？");
  if (!isif) return;
  await SubmitAPI({ idList: state.ids });

  getList();
  delDisabled.value = true;
  initBtn();
  close();
  proxy.successMsg("提交成功！");
};

// 审核弹窗
const audit = async (id) => {
  tabPosition.value = "2";
  state.title = "审核";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.id = id;
    state.examineShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 修改弹窗
const editDic = async (id) => {
  tabPosition.value = "1";
  state.title = "修改";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 查看弹窗
const seeDic = async (id) => {
  tabPosition.value = "1";
  state.title = "查看";
  proxy.loading("请求中，请稍后");
  try {
    const { data: res } = await GetDeiltsAPI(id);
    ruleForm.value = res;
    state.isShow = true;
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

//通过title判断执行事件
const isSub = () => {
  if (state.title == "新增") addSub();
  if (state.title == "修改") editSub();
  if (state.title == "派工") workersSub();
  if (state.title == "执行维修") maintenanceSub();
};

// 新增提交后台
const addSub = async () => {
  const WorkOrder = await WorkOrderRef.value.submit();
  const Failure = await FailureRef.value.submit();
  const Maintenance = await MaintenanceRef.value.submit();
  if (!(WorkOrder && Failure && Maintenance)) return;
  state.btnloading = true;
  try {
    await AddDataAPI({ ...Failure, ...WorkOrder, ...Maintenance });
    getList();
    close();
    proxy.successMsg("新增成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 修改提交后台
const editSub = async () => {
  const WorkOrder = await WorkOrderRef.value.submit();
  const Failure = await FailureRef.value.submit();
  const Maintenance = await MaintenanceRef.value.submit();
  if (!(WorkOrder && Failure && Maintenance)) return;
  state.btnloading = true;
  try {
    await EditDataAPI({ ...Failure, ...WorkOrder, ...Maintenance });
    getList();
    close();
    proxy.successMsg("修改成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 派工提交
const workersSub = async () => {
  const maintenance = await MaintenanceRef.value.submit();
  if (!maintenance) return;
  maintenance.idList = state.ids;
  maintenance.deviceCodeList = state.rows.map((t) => t.deviceCode);

  state.btnloading = true;
  try {
    await DispatchAPI({ ...maintenance });
    getList();
    close();
    proxy.successMsg("派工成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 执行维修提交
const maintenanceSub = async (id) => {
  const WorkOrder = await WorkOrderRef.value.submit();
  const Failure = await FailureRef.value.submit();
  const Maintenance = await MaintenanceRef.value.submit();
  if (!(WorkOrder && Failure && Maintenance)) return;
  state.btnloading = true;

  try {
    await MaintenanceAPI({ ...WorkOrder, ...Failure, ...Maintenance });
    getList();
    close();
    proxy.successMsg("执行维修成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 审核提交
const eamineSub = async (val) => {
  const Failure = await FailureRef.value.submit();
  if (!Failure) return;
  state.btnloading = true;
  try {
    await AuditAPI({
      repairId: Failure.repairId,
      repairWhether: val,
      repairOpinion: Failure.repairOpinion,
      repairCode: Failure.repairCode,
    });

    getList();

    state.examineShow = false;
    proxy.successMsg("审核成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

/**
 *批量撤销
 */
const revokeBacth = async () => {
  proxy.loading();
  try {
    const isif = await proxy.MessageBox("是否确认撤销审核？");
    if (!isif) return;
    await RatchRevocationAPI({ idList: state.ids });
    getList();
    delDisabled.value = true;
    initBtn();
    proxy.successMsg("撤销成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

/**
 * 批量审核
 * @param {*} ids
 */

const examineBacth = async () => {
  state.title = "审核";
  state.examineBatchShow = true;
};

/**
 * 批量审核提交
 */

const eamineBatchSub = async (val) => {
  const result = await ruleFormRef.value.validate();
  if (!result) return;
  console.log();
  state.btnloading = true;
  try {
    await BatchAuditAPI({
      idList: state.ids,
      repairWhether: val,
      repairOpinion: ruleForm.value.auditOpinion,
    });

    getList();
    delDisabled.value = true;
    initBtn();
    state.examineBatchShow = false;
    proxy.successMsg("审核成功！");
  } catch (err) {
    console.error(err);
  } finally {
    state.btnloading = false;
  }
};

// 删除
const remove = async (id) => {
  const isif = await proxy.DelMessageBox();
  if (!isif) return;
  proxy.loading("删除中，请稍后");
  try {
    await DelDataAPI(id);
    getList();
    close();
    proxy.successMsg("删除成功！");
  } catch (err) {
    console.error(err);
  } finally {
    proxy.closeLoading();
  }
};

// 弹窗取消
const close = () => {
  state.isShow = false;
  ruleForm.value = {};
};

// 获取列表数据
const getList = async () => {
  state.loading = false;
  try {
    const res = await GetListAPI(query);
    state.total = res.total;
    tabelData.value = res.rows;
  } catch (err) {
    console.error(err);
  } finally {
    state.loading = false;
  }
};

// 添加知识库
const add = async (id) => {
  try {
    const MesBox = await proxy.DelMessageBox("是否添加知识库");
    if (!MesBox) return;
    await AddKnowLedgeAPI(id);
    proxy.successMsg("添加成功");
    close();
    getList();
  } catch (err) {
  } finally {
  }
};
// getList()
/**
 * 判断是否从审核待办
 */
onMounted(() => {
  if (route.query.value) {
    query.repairId = route.query.value;
  }
  getList();
});
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <p-table
        :loading="state.loading"
        keyId="repairId"
        :column="column"
        :data="tabelData"
        @change="handleSelectionChange"
        :total="state.total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      >
        <template #buttons>
          <!-- 按钮组件 -->
          <p-button
            :list="btnList"
            @add="repair"
            @dispatch="workers"
            @examine="examineBacth"
            @review="subAudit"
            @revoke="revokeBacth"
          />
        </template>
        <template #columnCell="{ column, record }">
          <p-dictTag
            v-if="column.prop == 'repairState'"
            :options="equipment_repair_status"
            :value="record.repairState"
          />
          <p-operate
            v-if="column.prop == 'x'"
            :list="[
              // {
              //   icon: 'Edit',
              //   emit: 'edit',
              //   text: '修改',
              //   type: 'primary',
              //   disabled: record.repairState != 1 && record.repairState != 6,
              //   hasPermi: 'device:workorder:edit',
              // },
              {
                icon: 'Delete',
                emit: 'remove',
                text: '删除',
                type: 'danger',
                disabled: record.repairState != 1,
                hasPermi: 'device:repair:equipment:remove',
              },
              {
                icon: 'Search',
                emit: 'look',
                text: '查看',
                type: 'primary',
                hasPermi: 'device:repair:equipment:query',
              },
              // {
              //   icon: '',
              //   emit: 'dispatch',
              //   text: '派工',
              //   type: 'primary',
              //   disabled: record.repairState != 1 && record.repairState != 6,
              //   hasPermi: 'device:workorder:dispatch',
              // },

              {
                icon: '',
                emit: 'examine',
                text: '审核单据',
                type: 'primary',
                disabled: record.repairState != 4,
                hasPermi: 'device:repair:equipment:examine',
              },

              {
                icon: '',
                emit: 'knowledge',
                text: '添加知识库',
                type: 'primary',
                disabled: record.repairState != 6,
                hasPermi: 'device:repair:equipment:knowledge',
              },
            ]"
            @edit="editDic(record.repairId)"
            @remove="remove(record.repairId)"
            @look="seeDic(record.repairId)"
            @maintenance="maintenance(record.repairId)"
            @review="subAudit(record.repairId)"
            @examine="audit(record.repairId)"
            @knowledge="add(record.repairId)"
          />
        </template>
      </p-table>
    </el-card>
    <!-- 报修 || 修改 || 查看弹框 -->
    <p-dialog
      v-model="state.isShow"
      @ok="isSub"
      :loading="state.btnloading"
      :title="state.title"
      @close="close"
      width="60%"
    >
      <template #body>
        <el-tabs v-model="tabPosition">
          <el-tab-pane name="1" label="工单信息" v-if="state.title != '派工'">
            <WorkOrder
              ref="WorkOrderRef"
              :disabled="state.title == '查看'"
              :title="state.title"
              :data="ruleForm"
            />
          </el-tab-pane>
          <el-tab-pane name="2" label="故障信息" v-if="state.title != '派工'">
            <Failure
              ref="FailureRef"
              :disabled="state.title == '查看'"
              :title="state.title"
              :data="ruleForm"
            />
          </el-tab-pane>
          <el-tab-pane name="3" label="维修信息" v-if="state.title != '派工'">
            <Maintenance
              ref="MaintenanceRef"
              :disabled="state.title == '查看'"
              :title="state.title"
              :data="ruleForm"
            />
          </el-tab-pane>
        </el-tabs>
      </template>
    </p-dialog>

    <!-- 批量审核弹窗 -->
    <p-dialog
      :loading="state.btnloading"
      isEamine
      v-model="state.examineBatchShow"
      width="30%"
      :title="state.title"
      @ok="eamineBatchSub"
      @close="close"
    >
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="审核意见">
          <el-input
            clearable
            v-model="ruleForm.auditOpinion"
            type="textarea"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div style="text-align: center">共计{{ state.rows.length }}审核单据</div>
    </p-dialog>
    <!-- 审核弹窗 -->
    <p-dialog
      :loading="state.btnloading"
      isEamine
      v-model="state.examineShow"
      width="60%"
      :title="state.title"
      @ok="eamineSub"
      @close="close"
    >
      <p-auditHistory title="基本信息" :auditDoc="state.id">
        <el-tabs v-model="tabPosition">
          <el-tab-pane name="1" label="工单信息">
            <WorkOrder
              ref="WorkOrderRef"
              :disabled="state.title == '查看'"
              :title="state.title"
              :data="ruleForm"
            />
          </el-tab-pane>
          <el-tab-pane name="2" label="故障信息">
            <Failure
              ref="FailureRef"
              :disabled="state.title == '查看'"
              :title="state.title"
              :data="ruleForm"
            />
          </el-tab-pane>
          <el-tab-pane name="3" label="维修信息" v-if="state.title != '新增'">
            <Maintenance
              ref="MaintenanceRef"
              :disabled="state.title == '查看'"
              :title="state.title"
              :data="ruleForm"
            />
          </el-tab-pane>
        </el-tabs>
      </p-auditHistory>
    </p-dialog>
  </div>
</template>

<style lang="scss" scoped>
.box-card {
  margin-top: 20px;
}

.demo-tabs {
  height: 100%;
}
</style>